<template>
  <div class="meeting-management">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="会议名称">
          <el-input v-model="searchForm.MeetName" placeholder="请输入会议名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>会议列表</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>新增会议
          </el-button>
        </div>
      </template>

      <el-table 
        :data="tableData" 
        style="width: 100%"
        border
        stripe
        highlight-current-row
        v-loading="loading"
      >
        <el-table-column prop="MeetManagerId" label="会议ID" width="100" />
        <el-table-column prop="MeetName" label="会议名称" width="200" />
        <el-table-column label="会议图片" width="120">
          <template #default="{ row }">
            <el-image 
              :src="row.MeetPhoto" 
              :preview-src-list="[row.MeetPhoto]"
              fit="cover"
              style="width: 80px; height: 80px"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="MeetPeopleNum" label="入会人数" width="120" />
        <el-table-column prop="MeetAddr" label="会议位置" width="200" />
        <el-table-column prop="MeetAdmin" label="会议管理员" width="120" />
        <el-table-column prop="AdminTel" label="管理员电话" width="150" />
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleDetail(row)">
              <el-icon><View /></el-icon>详情
            </el-button>
            <el-button link type="primary" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button link type="danger" size="small" @click="handleDelete(row.MeetManagerId)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="LookData.PageIndex"
          v-model:page-size="LookData.PageSize"
          :page-sizes="[5, 10, 20, 30]"
          :total="LookData.TotalCount"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-card>

    <!-- 会议详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="会议详情" width="500px">
      <el-form label-width="100px">
        <el-form-item label="会议名称">
          <el-input :model-value="displayValue(currentMeetingDetail.MeetName)" disabled />
        </el-form-item>
        <el-form-item label="会议图片">
          <el-image 
            :src="currentMeetingDetail.MeetPhoto" 
            :preview-src-list="[currentMeetingDetail.MeetPhoto]"
            fit="cover"
            style="width: 200px; height: 200px"
          >
            <template #error>
              <div class="image-slot">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
        </el-form-item>
        <el-form-item label="入会人数">
          <el-input :model-value="displayValue(currentMeetingDetail.MeetPeopleNum)" disabled />
        </el-form-item>
        <el-form-item label="会议位置">
          <el-input :model-value="displayValue(currentMeetingDetail.MeetAddr)" disabled />
        </el-form-item>
        <el-form-item label="会议管理员">
          <el-input :model-value="displayValue(currentMeetingDetail.MeetAdmin)" disabled />
        </el-form-item>
        <el-form-item label="管理员电话">
          <el-input :model-value="displayValue(currentMeetingDetail.AdminTel)" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑会议对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑会议" width="500px">
      <el-form ref="editFormRef" :model="currentEditingMeeting" :rules="addRules" label-width="100px">
        <el-form-item label="会议名称" prop="MeetName">
          <el-input v-model="currentEditingMeeting.MeetName" placeholder="请输入会议名称" />
        </el-form-item>
        <el-form-item label="容纳人数" prop="MeetPeopleNum">
           <el-select v-model="currentEditingMeeting.MeetPeopleNum" placeholder="请选择容纳人数">
             <el-option
                v-for="item in peopleNumOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
             />
           </el-select>
        </el-form-item>
        <el-form-item label="会议位置" prop="MeetAddr">
           <el-select v-model="currentEditingMeeting.MeetAddr" placeholder="请选择会议位置">
              <el-option
                v-for="item in meetAddrOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
           </el-select>
        </el-form-item>
        <el-form-item label="会议管理员" prop="MeetAdmin">
           <el-input v-model="currentEditingMeeting.MeetAdmin" placeholder="请输入会议管理员" />
        </el-form-item>
        <el-form-item label="联系电话" prop="AdminTel">
           <el-input v-model="currentEditingMeeting.AdminTel" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="会议图片" prop="MeetPhoto">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:5293/api/Meet/UpPhoto"
            :show-file-list="false"
            :on-success="handleEditAvatarSuccess"
            :before-upload="beforeEditAvatarUpload"
          >
            <img v-if="currentEditingMeeting.MeetPhoto" :src="currentEditingMeeting.MeetPhoto" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
         <el-form-item>
            <el-checkbox v-model="currentEditingMeeting.IsBooking">预约审批</el-checkbox>
            <el-checkbox v-model="currentEditingMeeting.IsMeetRoom">智能会议室</el-checkbox>
         </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增会议对话框 -->
    <el-dialog v-model="addDialogVisible" title="新增会议室" width="500px">
      <el-form ref="addFormRef" :model="addForm" :rules="addRules" label-width="100px">
        <el-form-item label="会议名称" prop="MeetName">
          <el-input v-model="addForm.MeetName" placeholder="请输入会议名称" />
        </el-form-item>
        <el-form-item label="容纳人数" prop="MeetPeopleNum">
           <el-select v-model="addForm.MeetPeopleNum" placeholder="请选择容纳人数">
             <el-option
                v-for="item in peopleNumOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
             />
           </el-select>
        </el-form-item>
        <el-form-item label="会议位置" prop="MeetAddr">
           <el-select v-model="addForm.MeetAddr" placeholder="请选择会议位置">
              <el-option
                v-for="item in meetAddrOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
           </el-select>
        </el-form-item>
        <el-form-item label="会议管理员" prop="MeetAdmin">
           <el-input v-model="addForm.MeetAdmin" placeholder="请输入会议管理员" />
        </el-form-item>
        <el-form-item label="联系电话" prop="AdminTel">
           <el-input v-model="addForm.AdminTel" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="会议图片" prop="MeetPhoto">
           <el-upload
              class="avatar-uploader"
              action="http://localhost:5293/api/Meet/UpPhoto"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="addForm.MeetPhoto" :src="addForm.MeetPhoto" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
        </el-form-item>
         <el-form-item>
            <el-checkbox v-model="addForm.IsBooking">预约审批</el-checkbox>
            <el-checkbox v-model="addForm.IsMeetRoom">智能会议室</el-checkbox>
         </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { GetMeetList } from '@/api/Readapi'
import { DelMeet, UpPhoto, AddMeet, UpdateMeet } from '@/api/Writeapi'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Search, Refresh, Plus, View, Edit, Delete, Picture } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'

interface ApiResponse {
  code: number
  msg: string
  data: any
}

const loading = ref(false)
const tableData = ref([])

const searchForm = reactive({
  MeetName: ''
})

const LookData = reactive({
  PageIndex: 1,
  PageSize: 5,
  MeetName: '',
  TotalCount: 0,
  TotalPage: 0
})

const detailDialogVisible = ref(false)
const currentMeetingDetail = ref<any>({})

const addDialogVisible = ref(false)
const addFormRef = ref<FormInstance>()
const addForm = reactive<any>({
  MeetName: '',
  MeetPhoto: '',
  MeetPeopleNum: '',
  MeetAddr: '',
  MeetAdmin: '',
  AdminTel: '',
  IsBooking: false,
  IsMeetRoom: false,
})

const peopleNumOptions = [
  { label: '11-20人', value: '11-20人' },
  { label: '21-50人', value: '21-50人' }
]

const meetAddrOptions = [
  { label: '办公楼501', value: '办公楼501' },
  { label: '办公楼502', value: '办公楼502' },
  { label: '办公楼503', value: '办公楼503' },
  { label: '办公楼504', value: '办公楼504' },
  { label: '办公楼505', value: '办公楼505' },
  { label: '行政楼-101', value: '行政楼-101' },
  { label: '行政楼-201', value: '行政楼-201' },
  { label: '行政楼-301', value: '行政楼-301' },
  { label: '行政楼-401', value: '行政楼-401' },
  { label: '行政楼-501', value: '行政楼-501' }
]

const addRules = reactive<FormRules<typeof addForm>>({
  MeetName: [
    { required: true, message: '请输入会议名称', trigger: 'blur' },
  ],
  MeetPeopleNum: [
     { required: true, message: '请选择容纳人数', trigger: 'change' },
  ],
  MeetAddr: [
     { required: true, message: '请选择会议位置', trigger: 'change' },
  ],
  MeetAdmin: [
     { required: true, message: '请输入会议管理员', trigger: 'blur' },
  ],
  AdminTel: [
     { required: true, message: '请输入管理员电话', trigger: 'blur' },
  ],
  MeetPhoto: [
    { required: true, message: '请上传会议图片', trigger: 'change' },
  ]
})

// Function to display "空值" if value is null, undefined, or empty string
const displayValue = (value: any) => {
  if (value === null || value === undefined || value === '' || (typeof value === 'number' && isNaN(value))) {
    return ''
  }
  return value
}

//#region
// 搜索
const handleSearch = () => {
  LookData.PageIndex = 1
  LookData.MeetName = searchForm.MeetName
  GetData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.MeetName = ''
  handleSearch()
}

// 获取数据
const GetData = async () => {
  try {
    loading.value = true
    const res = await GetMeetList({
      PageIndex: LookData.PageIndex,
      PageSize: LookData.PageSize,
      MeetName: LookData.MeetName
    }) as unknown as ApiResponse
    console.log(res)
     if (res.code === 200 && res.data && res.data.data) {
        tableData.value = res.data.data;
        LookData.TotalCount = res.data.TotalCount;
        LookData.TotalPage = res.data.TotalPage;
    } else {
        ElMessage.error(res.msg || '获取会议列表失败');
        tableData.value = [];
        LookData.TotalCount = 0;
        LookData.TotalPage = 0;
    }
  } catch (error) {
    console.error('获取会议列表失败:', error)
    ElMessage.error('获取会议列表失败')
    tableData.value = [];
    LookData.TotalCount = 0;
    LookData.TotalPage = 0;
  } finally {
    loading.value = false
  }
}

// 改变页容量
const handleSizeChange = (val: number) => {
  LookData.PageSize = val
  GetData()
}

// 改变页码
const handleCurrentChange = (val: number) => {
  LookData.PageIndex = val
  GetData()
}

//#endregion

// 打开新增会议对话框
const handleAdd = () => {
  // Reset form and open dialog
  if (addFormRef.value) {
    addFormRef.value.resetFields();
  }
  addForm.MeetName = '';
  addForm.MeetPhoto = '';
  addForm.MeetPeopleNum = '';
  addForm.MeetAddr = '';
  addForm.MeetAdmin = '';
  addForm.AdminTel = '';
  addForm.IsBooking = false;
  addForm.IsMeetRoom = false;
  addDialogVisible.value = true;
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  // addForm.value = URL.createObjectURL(uploadFile.raw!)
  addForm.MeetPhoto = response // 假设response就是图片URL字符串
  console.log(addForm.MeetPhoto)
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' ) {
    ElMessage.error('图片格式必须是 JPG 或 PNG!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 提交新增会议表单
const submitAddForm = async () => {
  if (!addFormRef.value) return;

  await addFormRef.value.validate(async (valid) => {
    if (valid) {
      // Form is valid, submit data
      try {
        const res = await AddMeet(addForm) as unknown as ApiResponse;
        if (res.code === 200) {
          ElMessage.success('会议添加成功');
          addDialogVisible.value = false; // Close dialog
          GetData(); // Refresh list
        } else {
          ElMessage.error(res.msg || '会议添加失败');
        }
      } catch (error) {
        console.error('添加会议失败:', error);
        ElMessage.error('添加会议失败');
      }
    } else {
      console.log('Form validation failed');
      ElMessage.warning('请填写完整必填项');
    }
  });
};

// 查看详情
const handleDetail = (row: any) => {
  currentMeetingDetail.value = row
  detailDialogVisible.value = true
}

// 编辑会议
const handleEdit = (row: any) => {
  currentEditingMeeting.value = { ...row }; // 复制行数据到编辑表单
  editDialogVisible.value = true;
}
//#region

// 删除会议
const handleDelete = (id: any) => {
  ElMessageBox.confirm(
    '确定要删除该会议吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await DelMeet(id) as unknown as ApiResponse
      if (res.code === 200) {
        ElMessage.success('删除成功')
        GetData()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除会议失败:', error)
      ElMessage.error('删除会议失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

//#endregion

onMounted(() => {
  GetData()
})

const editDialogVisible = ref(false);
const currentEditingMeeting = ref<any>({});
const editFormRef = ref<FormInstance>();

// 提交编辑会议表单
const submitEditForm = async () => {
  if (!editFormRef.value) return;

  await editFormRef.value.validate(async (valid) => {
    if (valid) {
        const res = await UpdateMeet(currentEditingMeeting.value) as unknown as ApiResponse;
        if (res.code === 200) {
          ElMessage.success('会议修改成功');
          editDialogVisible.value = false; // Close dialog
          GetData(); // Refresh list
        } else {
          ElMessage.error(res.msg);
        }
    } else {
      console.log('Form validation failed');
      ElMessage.warning('请填写完整必填项');
    }
  });
};

const handleEditAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  currentEditingMeeting.value.MeetPhoto = response
}

const beforeEditAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' ) {
    ElMessage.error('图片格式必须是 JPG 或 PNG!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}
</script>


<style scoped>
.meeting-management {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

:deep(.el-table) {
  margin-top: 10px;
}

:deep(.el-button) {
  margin-left: 8px;
}

:deep(.el-button:first-child) {
  margin-left: 0;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 20px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style> 
